package br.unisinos.tetris.state;

import java.awt.BorderLayout;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;

import br.unisinos.tetris.pieces.FlyweightPiece;
import br.unisinos.tetris.pieces.Piece;

public abstract class PieceState {

	private JLabel jLabel;
	private Piece piece;
	private JLabel previousJLabel;
	
	public PieceState(PieceState previousState, Piece piece, int angle) {
		this.piece = piece;
		try {
			BufferedImage bimg = FlyweightPiece.getPieceImage(piece);
			if (angle > 0) {
				bimg = rotate(bimg, angle);
				piece.setHeight(bimg.getHeight());
				piece.setWidth(bimg.getWidth());
			}
			jLabel = new JLabel(new ImageIcon(bimg));
			if (previousState != null) {
				previousJLabel = previousState.getJLabel();	
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public Piece getPiece() {
		return piece;
	}
	
	public JLabel getJLabel() {
		return jLabel;
	}
	
	public void paint(JPanel c) {
		if (previousJLabel != null) {
			c.remove(previousJLabel);
			this.previousJLabel = null;
		}
		c.remove(jLabel);
		jLabel.setBounds(piece.getX(), piece.getY(), piece.getHeight(), piece.getWidth());
		c.add(jLabel, BorderLayout.NORTH);
	}
	
	public abstract PieceState getNextState();
	
	protected static BufferedImage rotate(BufferedImage img, int angle) {
		int w = img.getWidth();
		int h = img.getHeight();
		BufferedImage dimg = dimg = new BufferedImage(w, h, img.getType());
		Graphics2D g = dimg.createGraphics();
		g.rotate(Math.toRadians(angle), w / 2, h / 2);
		g.drawImage(img, null, 0, 0);
		return dimg;
	}
	
}
